#!/bin/bash

[ "$#" = "1" ] || { echo "Usage: $(basename "$0") filename_of_image"; exit 1; }

CWD=$(pwd)
BUSYBOX=busybox-1.33.1
CP=/bin/cp 
RM=/bin/rm
TMPDIR=$(mktemp -d .tmp.XXXXXXXX)
cd $TMPDIR

mkdir -p dev/pts etc/init.d mnt/share var/run/netns proc root sys tmp lib64 var/log usr/share/udhcpc
chmod a+rwxt tmp

make -C $CWD/$BUSYBOX install -j$(nproc)
$CP -rf $CWD/$BUSYBOX/_install/* ./
$CP -rf $CWD/$BUSYBOX/examples/udhcp/simple.script ./usr/share/udhcpc/default.script
$CP /lib64/{libnss_dns,libresolv,ld-linux-x86-64}.so.2 /lib64/{libc,libm}.so.6 ./lib64
$CP /usr/lib/{libbpf.so.1,libelf.so.1,libz.so.1,libmnl.so.0,libcap.so.2,libzstd.so.1}  ./lib64
$CP -f /usr/sbin/ip ./sbin/ip2
$RM ./linuxrc
(cd ./usr/; ln -s ../lib64 lib; ln -s ../lib64 lib64)

cat << EOF > etc/inittab
::sysinit:/etc/init.d/rcS
::respawn:-/bin/sh
::askfirst:-/bin/sh
::ctrlaltdel:/bin/umount -a -r
EOF
cat << EOF > etc/fstab
proc   /proc		proc	defaults  0  0
sysfs  /sys		sysfs	defaults  0  0
tmpfs  /tmp		tmpfs	defaults  0  0
devpts /dev/pts		devpts	defaults  0  0
share  /mnt/share 	9p	defaults  0  0
EOF
cat << EOF > etc/init.d/rcS
#!bin/sh
umask 022
/bin/mount -a
echo /sbin/mdev > /proc/sys/kernel/hotplug
/sbin/mdev -s
/bin/hostname "fjrti"
ifconfig lo 127.0.0.1 up
udhcpc eth0
telnetd
EOF
cat << "EOF" > etc/profile
ulimit -S -c 0 > /dev/null 2>&1
USER="`id -un`"
LOGNAME=$USER
PS1='[\u@\h \W]\# '
PATH=$PATH
HOSTNAME=`/bin/hostname`
export USER LOGNAME PS1 PATH HOSTNAME
EOF
chmod 755 etc/inittab
chmod 755 etc/init.d/rcS
echo 'root:DANF2exHVlG0o:0:0:root:/root:/bin/sh' > etc/passwd
chmod 755 etc/passwd
cd dev
mknod tty c 5 0
mknod console c 5 1
mknod null c 1 3
mknod zero c 1 5
cd ..

find ./ | cpio -o -H newc | gzip > $CWD/${1}

cd $CWD
$RM -r $TMPDIR

exit 0
